import React, { useState, useEffect } from 'react';
import { View, Text, TextInput, TouchableOpacity, StyleSheet, Alert, ScrollView, Modal } from 'react-native';
import { useNavigation, useRoute } from '@react-navigation/native';
import AsyncStorage from '@react-native-async-storage/async-storage';
import Icon from 'react-native-vector-icons/Ionicons';
import I18n from '../utils/i18n';

const defaultMoodOptions = [
    { emoji: '😊', label: I18n.t('happy') },
    { emoji: '😢', label: I18n.t('sad') },
    { emoji: '😠', label: I18n.t('getAngry') },
    { emoji: '😍', label: I18n.t('excitement') },
    { emoji: '😎', label: I18n.t('cool') },
    { emoji: '🤔', label: I18n.t('reflection') },
    { emoji: '😴', label: I18n.t('tiredOut') },
    { emoji: '🙃', label: I18n.t('but') },
];

const MoodSettingPage = () => {
    const [selectedMood, setSelectedMood] = useState(null);
    const [description, setDescription] = useState('');
    const [isProfileSet, setIsProfileSet] = useState(false);
    const [customEmoji, setCustomEmoji] = useState('');
    const [customLabel, setCustomLabel] = useState('');
    const [moodOptions, setMoodOptions] = useState(defaultMoodOptions);
    const [isModalVisible, setIsModalVisible] = useState(false);
    const [isDeleteMode, setIsDeleteMode] = useState(false);
    const navigation = useNavigation();
    const route = useRoute();

    useEffect(() => {
        checkProfile();
        loadCustomMoods();
        loadTodayMood();
    }, []);

    const checkProfile = async () => {
        const userName = await AsyncStorage.getItem('userName');
        setIsProfileSet(!!userName);
        if (!userName) {
            Alert.alert(
                I18n.t('checkProfile.title'),
                I18n.t('checkProfile.content'),
                [
                    { text: I18n.t('goto'), onPress: () => navigation.navigate('Profile') }
                ]
            );
        }
    };

    const loadCustomMoods = async () => {
        try {
            const customMoods = await AsyncStorage.getItem('customMoods');
            if (customMoods) {
                setMoodOptions([...defaultMoodOptions, ...JSON.parse(customMoods)]);
            }
        } catch (error) {
            console.error('Error loading custom moods:', error);
        }
    };

    const loadTodayMood = async () => {
        try {
            const savedMood = await AsyncStorage.getItem('currentMood');
            if (savedMood) {
                const parsedMood = JSON.parse(savedMood);
                const moodDate = new Date(parsedMood.date);
                const today = new Date();
                if (moodDate.toDateString() === today.toDateString()) {
                    setSelectedMood(parsedMood.mood);
                    setDescription(parsedMood.description);
                }
            }
        } catch (error) {
            console.error('Error loading today\'s mood:', error);
        }
    };

    const handleSaveMood = async () => {
        if (!selectedMood) {
            Alert.alert(I18n.t('handleSaveMood.title'), I18n.t('handleSaveMood.content'));
            return;
        }

        try {
            const currentDate = new Date().toISOString();
            const moodEntry = {
                mood: selectedMood,
                description,
                date: currentDate
            };

            // 保存当前心情
            await AsyncStorage.setItem('currentMood', JSON.stringify(moodEntry));

            // 更新心情历史
            const history = await AsyncStorage.getItem('moodHistory');
            let moodHistory = history ? JSON.parse(history) : [];
            const todayIndex = moodHistory.findIndex(entry =>
                new Date(entry.date).toDateString() === new Date().toDateString()
            );

            if (todayIndex !== -1) {
                // 如果今天已经有记录，更新它
                moodHistory[todayIndex] = moodEntry;
            } else {
                // 如果今天还没有记录，添加新记录
                moodHistory.push(moodEntry);
            }

            // 只保留最近30天的记录
            moodHistory = moodHistory.slice(-30);

            await AsyncStorage.setItem('moodHistory', JSON.stringify(moodHistory));

            Alert.alert(I18n.t('success'), I18n.t('mood_saved'), [
                { text: I18n.t('OK'), onPress: () => navigation.goBack() }
            ]);
        } catch (error) {
            console.error('Error saving mood:', error);
            Alert.alert(I18n.t('error'), I18n.t('mood_error'));
        }
    };

    const handleAddCustomEmoji = async () => {
        if (customEmoji && customLabel) {
            const newMoodOption = { emoji: customEmoji, label: customLabel };
            try {
                const newMoodOptions = [...moodOptions, newMoodOption];
                setMoodOptions(newMoodOptions);
                const customMoods = newMoodOptions.filter(mood => !defaultMoodOptions.includes(mood));
                await AsyncStorage.setItem('customMoods', JSON.stringify(customMoods));
                setCustomEmoji('');
                setCustomLabel('');
                setIsModalVisible(false);
            } catch (error) {
                console.error('Error saving custom emoji:', error);
                Alert.alert(I18n.t('error'), I18n.t('failed_to_save_custom_emoji'));
            }
        } else {
            Alert.alert(I18n.t('error'), I18n.t('please_enter_emoticons_and_tags'));
        }
    };

    const handleDeleteCustomEmoji = async (emojiToDelete) => {
        try {
            const updatedMoodOptions = moodOptions.filter(mood =>
                mood.emoji !== emojiToDelete.emoji || mood.label !== emojiToDelete.label
            );
            setMoodOptions(updatedMoodOptions);
            const customMoods = updatedMoodOptions.filter(mood => !defaultMoodOptions.includes(mood));
            await AsyncStorage.setItem('customMoods', JSON.stringify(customMoods));
            Alert.alert(I18n.t('success'), I18n.t('custom_emoticon_deleted'));
        } catch (error) {
            console.error('Error deleting custom emoji:', error);
            Alert.alert(I18n.t('error'), I18n.t('failed_to_delete_custom_emoji'));
        }
    };

    const toggleDeleteMode = () => {
        setIsDeleteMode(!isDeleteMode);
    };

    if (!isProfileSet) {
        return (
            <View style={styles.container}>
                <Text style={styles.title}>{I18n.t('please_set_personal_information_first')}</Text>
                <TouchableOpacity style={styles.setProfileButton} onPress={() => navigation.navigate('Profile')}>
                    <Icon name="person-add-outline" size={24} color="#fff" />
                    <Text style={styles.setProfileButtonText}>{I18n.t('go_set_personal_information')}</Text>
                </TouchableOpacity>
            </View>
        );
    }

    return (
        <View style={styles.container}>
            <Text style={styles.title}>{selectedMood ? I18n.t('change_today_s_mood') : I18n.t('choose_today_s_mood')}</Text>
            <ScrollView contentContainerStyle={styles.moodContainer}>
                {moodOptions.map((mood) => (
                    <TouchableOpacity
                        key={`${mood.emoji}-${mood.label}`}
                        style={[
                            styles.moodButton,
                            selectedMood && selectedMood.emoji === mood.emoji && styles.selectedMood
                        ]}
                        onPress={() => isDeleteMode && !defaultMoodOptions.includes(mood) ?
                            handleDeleteCustomEmoji(mood) : setSelectedMood(mood)}
                    >
                        <Text style={styles.moodEmoji}>{mood.emoji}</Text>
                        <Text style={styles.moodLabel}>{mood.label}</Text>
                        {isDeleteMode && !defaultMoodOptions.includes(mood) && (
                            <View style={styles.deleteIcon}>
                                <Icon name="close-circle" size={20} color="red" />
                            </View>
                        )}
                    </TouchableOpacity>
                ))}
                <TouchableOpacity
                    style={styles.addMoodButton}
                    onPress={() => setIsModalVisible(true)}
                >
                    <Icon name="add-outline" size={24} color="#333" />
                </TouchableOpacity>
            </ScrollView>
            <TouchableOpacity style={styles.toggleDeleteButton} onPress={toggleDeleteMode}>
                <Text style={styles.toggleDeleteButtonText}>
                    {isDeleteMode ? I18n.t('complete_deletion') : I18n.t('delete_custom_emoticons')}
                </Text>
            </TouchableOpacity>
            <TextInput
                style={styles.input}
                placeholder={I18n.t('describe_your_emotions')}
                value={description}
                onChangeText={setDescription}
                multiline
            />
            <TouchableOpacity style={styles.saveButton} onPress={handleSaveMood}>
                <Icon name="save-outline" size={24} color="#fff" />
                <Text style={styles.saveButtonText}>{I18n.t('Preserve')}</Text>
            </TouchableOpacity>

            <Modal
                animationType="slide"
                transparent={true}
                visible={isModalVisible}
                onRequestClose={() => setIsModalVisible(false)}
            >
                <View style={styles.modalView}>
                    <Text style={styles.modalTitle}>{I18n.t('add_custom_emoticons')}</Text>
                    <TextInput
                        style={styles.emojiInput}
                        placeholder={I18n.t('enter_emoticons')}
                        value={customEmoji}
                        onChangeText={setCustomEmoji}
                    />
                    <TextInput
                        style={styles.emojiInput}
                        placeholder={I18n.t('enter_label')}
                        value={customLabel}
                        onChangeText={setCustomLabel}
                    />
                    <TouchableOpacity style={styles.addButton} onPress={handleAddCustomEmoji}>
                        <Text style={styles.addButtonText}>{I18n.t('add_to')}</Text>
                    </TouchableOpacity>
                    <TouchableOpacity
                        style={styles.closeButton}
                        onPress={() => setIsModalVisible(false)}
                    >
                        <Text style={styles.closeButtonText}>{I18n.t('close')}</Text>
                    </TouchableOpacity>
                </View>
            </Modal>
        </View>
    );
};

const styles = StyleSheet.create({
    deleteIcon: {
        position: 'absolute',
        top: -5,
        right: -5,
    },
    toggleDeleteButton: {
        backgroundColor: '#f0f0f0',
        padding: 10,
        borderRadius: 5,
        marginBottom: 10,
    },
    toggleDeleteButtonText: {
        textAlign: 'center',
        color: '#333',
    },
    container: {
        flex: 1,
        padding: 20,
        backgroundColor: '#f5f5f5',
    },
    title: {
        fontSize: 24,
        fontWeight: 'bold',
        marginBottom: 20,
    },
    moodContainer: {
        flexDirection: 'row',
        flexWrap: 'wrap',
        justifyContent: 'center',
        marginBottom: 20,
    },
    moodButton: {
        width: 60,
        height: 60,
        justifyContent: 'center',
        alignItems: 'center',
        margin: 5,
        borderRadius: 30,
        backgroundColor: '#fff',
        shadowColor: '#000',
        shadowOffset: { width: 0, height: 2 },
        shadowOpacity: 0.1,
        shadowRadius: 4,
        elevation: 3,
    },
    selectedMood: {
        backgroundColor: '#e0e0e0',
    },
    moodEmoji: {
        fontSize: 30,
    },
    addMoodButton: {
        width: 60,
        height: 60,
        justifyContent: 'center',
        alignItems: 'center',
        margin: 5,
        borderRadius: 30,
        backgroundColor: '#f0f0f0',
        borderWidth: 2,
        borderColor: '#ccc',
        borderStyle: 'dashed',
    },
    input: {
        backgroundColor: '#fff',
        borderRadius: 10,
        padding: 15,
        marginBottom: 20,
        shadowColor: '#000',
        shadowOffset: { width: 0, height: 2 },
        shadowOpacity: 0.1,
        shadowRadius: 4,
        elevation: 3,
    },
    saveButton: {
        backgroundColor: '#4CAF50',
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center',
        padding: 15,
        borderRadius: 10,
    },
    saveButtonText: {
        color: 'white',
        fontSize: 18,
        marginLeft: 10,
    },
    setProfileButton: {
        backgroundColor: '#3498db',
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center',
        padding: 15,
        borderRadius: 10,
    },
    setProfileButtonText: {
        color: 'white',
        fontSize: 18,
        marginLeft: 10,
    },
    modalView: {
        margin: 20,
        backgroundColor: 'white',
        borderRadius: 20,
        padding: 35,
        alignItems: 'center',
        shadowColor: '#000',
        shadowOffset: {
            width: 0,
            height: 2
        },
        shadowOpacity: 0.25,
        shadowRadius: 4,
        elevation: 5
    },
    modalTitle: {
        fontSize: 20,
        fontWeight: 'bold',
        marginBottom: 15,
    },
    emojiInput: {
        height: 40,
        borderColor: 'gray',
        borderWidth: 1,
        borderRadius: 5,
        width: '100%',
        paddingHorizontal: 10,
        marginBottom: 20,
    },
    addButton: {
        backgroundColor: '#4CAF50',
        borderRadius: 5,
        padding: 10,
        elevation: 2,
        marginBottom: 10,
    },
    addButtonText: {
        color: 'white',
        fontWeight: 'bold',
        textAlign: 'center',
    },
    closeButton: {
        backgroundColor: '#2196F3',
        borderRadius: 5,
        padding: 10,
        elevation: 2,
    },
    closeButtonText: {
        color: 'white',
        fontWeight: 'bold',
        textAlign: 'center',
    },
});

export default MoodSettingPage;
